package com.xunua.NaoZiKongBai.NewsDetailsActivity;

import android.os.Bundle;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gyf.immersionbar.ImmersionBar;
import com.xunua.NaoZiKongBai.Base.MyActivity;
import com.xunua.NaoZiKongBai.Bean.ApiResponse.NewsDetails;
import com.xunua.NaoZiKongBai.Constant;
import com.xunua.NaoZiKongBai.R;
import com.xunua.NaoZiKongBai.Utils.TimeUtil;
import com.xunua.NaoZiKongBai.api.RetrofitApiService;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.imid.swipebacklayout.lib.SwipeBackLayout;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * mvp设计模式太繁琐了，此项目功能并不多，因此后续不写mvp了。
 */
public class NewsDetailsActivity extends MyActivity {
    @BindView(R.id.news_details_tv_appname)
    TextView newsDetailsTvAppname;
    @BindView(R.id.news_details_rel_titlebar)
    RelativeLayout newsDetailsRelTitlebar;
    @BindView(R.id.news_details_tv_title)
    TextView newsDetailsTvTitle;
    @BindView(R.id.news_details_tv_source)
    TextView newsDetailsTvSource;
    @BindView(R.id.news_details_tv_ptime)
    TextView newsDetailsTvPtime;
    @BindView(R.id.news_details_linelayout_context)
    LinearLayout newsDetailsLinelayoutContext;
    @BindView(R.id.news_details_webview)
    WebView newsDetailsWebview;
    private String newsId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_details);
        ButterKnife.bind(this);
        initStarBar();
        getSwipeBackLayout().setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT);//从左往右滑动关闭activity
        newsId = getIntent().getExtras().getString("NewsId", "");
        getnewsDetails();
    }

    private void initStarBar() {
        //标准模式
        ImmersionBar.with(this)
                .keyboardEnable(true)//解决软键盘与底部输入框冲突问题
                .statusBarDarkFont(true)//状态栏字体颜色
                .navigationBarColor(R.color.navigationBarcolor)//导航栏颜色，不写默认黑色
                .navigationBarDarkIcon(true)//导航栏图标是深色，不写默认为亮色
                .init();//沉浸状态栏
    }

    private void getnewsDetails() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.wanAndroid_baseurl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        HashMap params = Constant.getWanAndroidApiKey();
        params.put("newsId", newsId);
        retrofit.create(RetrofitApiService.class).getNewsDetails(params)
                .subscribeOn(Schedulers.io())
                .map(new Function<NewsDetails, NewsDetails.DataBean>() {
                    @Override
                    public NewsDetails.DataBean apply(NewsDetails newsDetails) throws Exception {
                        NewsDetails.DataBean data = newsDetails.getData();
                        if (data.getContent() == null) {
                            data.setContent("");
                        }
                        if (data.getCover() == null) {
                            data.setCover("");
                        }
                        if (data.getDocid() == null) {
                            data.setDocid("");
                        }
                        if (data.getPtime() != null) {
                            try {
                                Date date = TimeUtil.getDATE(data.getPtime());
                                String timeFormatText = TimeUtil.getTimeFormatText(date);
                                data.setPtime(timeFormatText);//转换数据格式，把他的时间转换为几天前的格式
                            } catch (Exception e) {
                                data.setPtime("");
                            }
                        }
                        if (data.getSource() == null) {
                            data.setSource("");
                        }
                        if (data.getTitle() == null) {
                            data.setTitle("");
                        }
                        return data;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<NewsDetails.DataBean>() {
                    @Override
                    public void onSubscribe(Subscription s) {
                        s.request(Long.MAX_VALUE);
                    }

                    @Override
                    public void onNext(NewsDetails.DataBean data) {
                        //解析数据 展示
                        initView(data);
                    }

                    @Override
                    public void onError(Throwable t) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void initView(NewsDetails.DataBean data) {
        newsDetailsTvTitle.setText(data.getTitle());
        newsDetailsTvSource.setText(data.getSource());
        newsDetailsTvPtime.setText(data.getPtime());
//        data.getImages().get()
//        data.getContent()
        initContent(data);
    }

    private boolean isloading;

    /**
     * 将正文数据以html的格式加载到webview中
     * @param data
     */
    private void initContent(NewsDetails.DataBean data) {
        String s=data.getContent();
        String[] a=s.split("<!--IMG#*[0-9]{0,3}-->");//000-999  只要接口不出问题，我就不会翻车
        StringBuilder sb=new StringBuilder();//内容
        for(int i=0;i<a.length;i++) {
            try {
                String src=data.getImages().get(i).getImgSrc();
                sb.append(a[i]+"<image src=\""+src+"\"/>");
            }catch (Exception e) {
                sb.append(a[i]);
            }
        }
        String html="<!DOCTYPE html>\n" +
                "<html>\n" +
                "\t<head>\n" +
                "\t\t<meta charset=\"utf-8\" />\n" +
                "\t\t<title></title>\n" +
                "\t\t<style type=\"text/css\">\n" +
                "\t\t\timg { height: auto; width: auto\\9; width:100%; }\n" +//使图片自适应
                "\t\t</style>\n" +
                "\t</head>\n" +
                "\t<body>\n" +
                sb+
                "\t</body>\n" +
                "</html>\n";


        newsDetailsWebview.loadData(html,null,null);
    }
}
